<template>
    <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
            <div class="manual-add-watch-wrap" v-loading="loading">
                <el-form label-width="100px" :model="manualAddClassesForm" :rules="manualAddClassesFormRules" ref="manualAddClassesForm" @submit.native.prevent>
                    <el-form-item label="日期：" prop='time'>
                        <el-date-picker
                            v-model="manualAddClassesForm.time"
                            :picker-options="pickerOptions"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </el-form-item>
                </el-form>
                <el-tabs type="border-card" v-if="showTabs" v-model="defalutTabName">
                    <el-tab-pane v-for="item in classesOptions" :key="item.id" :name="'watchRecord'+item.id">
                        <span slot="label">{{item.orderName}}</span>
                        <div>
                            <el-row>
                                <el-col :span="21">
                                    <p style="line-height: 28px;">{{item.startTime + '-' + item.endTime + '（ 跨' + item.daysInterval + '天 ）'}}</p>
                                </el-col>
                                <el-col :span="3">
                                    <el-tooltip class="item" effect="dark" content="添加值班人" placement="top-start">
                                        <el-button type="primary" icon="el-icon-plus" @click="addWatchPerson('watchRecord'+item.id, item)" size="mini"></el-button>
                                    </el-tooltip>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-form class="watch-record-from" v-for="(obj, index) in classesWatchList['watchRecord'+item.id]" :key="index" label-width="100px" :model="classesWatchList['watchRecord'+item.id][index]" :rules="watchInfoFormRules" ref="watchInfoForm" @submit.native.prevent>
                                    <!-- <el-form-item label="开始时间：" prop='watchStartTime'>
                                        <el-time-select
                                            v-model="obj.watchStartTime"
                                            :picker-options="{
                                                start: item.startTime,
                                                step: '00:05',
                                                end: item.endTime
                                            }"
                                            placeholder="选择开始时间">
                                        </el-time-select>
                                    </el-form-item>
                                    <el-form-item label="结束时间：" prop='watchEndTime'>
                                        <el-time-select
                                            v-model="obj.watchEndTime"
                                            :picker-options="{
                                                start: obj.watchStartTime || item.startTime,
                                                step: '00:05',
                                                end: item.endTime
                                            }"
                                            placeholder="选择结束时间">
                                        </el-time-select>
                                    </el-form-item> -->
                                    <el-row>
                                        <el-col :span="20">
                                            <el-form-item label="值班人：" prop='watchAccount'>
                                                <el-select filterable multiple v-model="obj.watchAccount">
                                                    <el-option
                                                        v-for="item in personnelOptions"
                                                        :key="item.accountName"
                                                        :label="item.name"
                                                        :value="item.accountName">
                                                    </el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="4">
                                            <el-button type="danger" icon="el-icon-delete" @click="deleteMultiLineForm('watchRecord'+item.id, index)" size="mini"></el-button>
                                        </el-col>
                                    </el-row>
                                </el-form>
                            </el-row>
                        </div>
                    </el-tab-pane>
                </el-tabs>
                <el-row class="verifyidentity-button">
                    <el-button @click.stop="closeFun" round>取消</el-button>
                    <el-button type="primary" @click="saveClassesWatchList" round>保存</el-button>
                </el-row>
            </div>
        </el-col>
    </el-row>
</template>
<script>
import * as Dao from '@/api/watch'
import {getUsers} from '@/api/api'

export default {
    name: 'ManualAddWatch',
    props: {
        organizationId: {
            required: true
        },
        closeFun: {
            type: Function,
            required: true
        }
    },
    data() {
        return {
            loading: false,
            showTabs: false,
            pickerOptions: {
                disabledDate: (time) => {
                    let nowData = new Date()
                    nowData = new Date(nowData.setDate(nowData.getDate()))
                    return time < nowData
                }
            },
            manualAddClassesForm: {
                time: ''
            },
            manualAddClassesFormRules: {
                time: [
                    { required: true, message: '请选择日期', trigger: 'change' },
                ]
            },
            watchInfoFormRules: {
                // watchStartTime: [
                //     { required: true, message: '请选择开始时间', trigger: 'change' },
                // ],
                // watchEndTime: [
                //     { required: true, message: '请选择结束时间', trigger: 'change' },
                // ],
                watchAccount: [
                    { required: true, message: '请选择值班人', trigger: 'change' },
                ]
            },
            defalutTabName: '',
            classesOptions: [], // 班次数据
            personnelOptions: [], // 值班人
            classesWatchList: {}, // 班次值班信息
            infoCount: 0
        }
    },
    created() {
        let that = this
        let parames = {
            organizationId: that.organizationId,
            sort: 'orderTimes',
            order: 'asc',
            offset: 0,
            limit: 20,
        }
        // 获取班次信息
        Dao.getClasses(parames).then(res => {
            // 初始化班次值班信息
            for(var i=0, len=res.data.length; i < len; i++) {
                if(i == 0) {
                    that.defalutTabName = 'watchRecord' + res.data[0].id
                }
                that.$set(that.classesWatchList, 'watchRecord'+res.data[i].id, [])
                // 零点转换成24点
                if(res.data[i].endTime == '00:00') {
                    res.data[i].endTime = '24:00'
                }
                // 班次跨天
                // if(res.data[i].daysInterval > 0) {
                //     res.data[i].endTime = String(Number(res.data[i].endTime.split(':')[0]) + 24*res.data[i].daysInterval) + ':' + res.data[i].endTime.split(':')[1]
                // }
            }
            that.classesOptions = res.data
            that.showTabs = true
        })
        // 获取值班人员
        getUsers({
            orgId: that.organizationId,
            queryType: 0
        }).then(res => {
           that.personnelOptions = res.data
        })
    },
    methods: {
        // 日期增加X天
        addDate(date, days) {
            if (days == undefined || days === '') {
                days = 1
            }
            var currentDate = new Date(date);
            currentDate.setDate(currentDate.getDate() + days)
            var month = currentDate.getMonth() + 1
            var day = currentDate.getDate()
            return currentDate.getFullYear() + '-' + this.getFormatDate(month) + '-' + this.getFormatDate(day)
        },
        // 日期月份/天的显示，如果是1位数，则在前面加上'0'
        getFormatDate(arg) {
            if (arg == undefined || arg == '') {
                return ''
            }
            var re = arg + ''
            if (re.length < 2) {
                re = '0' + re
            }
            return re
        },
        // 添加值班人
        addWatchPerson(key, row) {
            if(key) {
                let newWatch = {
                    watchStartTime: row.startTime,
                    watchEndTime: String(Number(row.endTime.split(':')[0]) + 24*row.daysInterval) + ':' + row.endTime.split(':')[1],
                    watchAccount: ''
                }
                this.infoCount += 1
                this.classesWatchList[key].push(newWatch)
            }
        },
        // 删除多行表单
        deleteMultiLineForm(key, index) {
            this.infoCount -= 1
            this.classesWatchList[key].splice(index, 1)
        },
        startEndDataFormat(date, time) {
            // 12:12
            if(time) {
                let timeArr = time.split(':') 
                // 26:00 时间跨天
                if(Number(timeArr[0]) > 24) {
                    let days = Math.floor(Number(timeArr[0])/24)
                    let HH = Number(timeArr[0]) - days*24
                    // 补差天数
                    return this.addDate(date, days) + ' ' + HH + ':' + timeArr[1] + ':00'
                }
                return date + ' ' + time + ':00'
            } else {
                return ''
            }
        },
        // 保存
        saveClassesWatchList() {
            let that = this
            let successCount = 0
            let multiLineFormValudate = true
            // 循环班次值班信息数据，一条信息发送一次保存接口
            if(that.infoCount > 0) {
                // 校验日期是否存在
                that.$refs['manualAddClassesForm'].validate((valid1) => {
                    if(valid1) {
                        // 校验多行表单
                        for(var n=0, len=that.$refs['watchInfoForm'].length; n < len; n++) {
                            that.$refs['watchInfoForm'][n].validate((valid2) => {
                                if(!valid2) {
                                    multiLineFormValudate = false
                                    return false
                                }
                            })
                        }
                        // 全部校验通过
                        if(multiLineFormValudate) {
                            for(var key in that.classesWatchList) {
                                let obj = that.classesWatchList[key]
                                for(var i=0, len=obj.length; i < len; i++) {
                                    that.loading = true
                                    // 日期
                                    let date = that.manualAddClassesForm.time
                                    // 保存值班信息
                                    Dao.updateDetails({
                                        id: 0,
                                        organizationId: that.organizationId,
                                        watchAccount: obj[i].watchAccount.join(','),
                                        watchClassId: Number(key.replace('watchRecord', '')),
                                        watchDate: Number(date.split('-').join('')),
                                        watchEndTime: that.startEndDataFormat(date, obj[i].watchEndTime),
                                        watchStartTime: that.startEndDataFormat(date, obj[i].watchStartTime)
                                    }).then(res => {
                                        if(res.status === 200) {
                                            successCount += 1
                                            // 全部提交完毕
                                            if(successCount == that.infoCount) {
                                                // 移除遮罩
                                                that.loading = false
                                                that.$message({
                                                    message: '保存成功',
                                                    type: 'success'
                                                })
                                                // 关闭弹框
                                                that.closeFun(true)
                                            }
                                        } else {
                                            that.$message.error(res.info)
                                            return false
                                        }
                                    })
                                }
                            }
                        }
                    } else {
                        return false
                    }
                })
            } else {
                that.$message({
                    message: '未添加值班人',
                    type: 'warning'
                })
            }
        }
    }
}
</script>
<style lang="scss">
.manual-add-watch-wrap {
    .watch-record-from {
        margin-top: 20px;
        border-bottom: 1px dashed #DCDFE6;
        .el-form-item {
            margin-bottom: 20px;
        }
        .el-button--danger {
            margin-top: 6px;
            margin-left: 20px;
        }
    }
}
</style>

